package com.app.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.xml.datatype.XMLGregorianCalendar;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Bean对象转化
 *
 * @author 闵渭凯
 * <p>
 * 2018年8月20日
 */
@Slf4j
public abstract class CommonBeanUtils extends org.springframework.beans.BeanUtils {



    /**
     * 对象赋值
     *
     * @param source 源对象
     * @param target 目标对象
     * @throws BeansException
     */
    public static void copyProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null) {
                            Method writeMethod = targetPd.getWriteMethod();
                            Type targetParameterType = writeMethod.getGenericParameterTypes()[0];
                            // 特殊类型不再执行copy XMLGregorianCalendar
                            if (!(targetParameterType.equals(XMLGregorianCalendar.class))) {
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                        }
                    } catch (Throwable ex) {
                        log.error(ex.getMessage());
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }

    /**
     * 集合对象转化赋值
     * @param sources 源集合对象
     * @param voClass vo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> copyListProperties(List<? extends Object> sources, final Class<T> voClass) {
        Assert.isTrue(!CollectionUtils.isEmpty(sources), "Source must not be null");
        List<T> targets = new ArrayList<>();
        sources.forEach(source -> {
            try {
                T target = voClass.newInstance();
                copyProperties(source, target);
                targets.add(target);
            } catch (InstantiationException | IllegalAccessException e) {
                log.error(e.getMessage());
            }
        });
        return targets;
    }

    /**
     * 将po对象的属性值赋值给dto对象相同属性名的属性
     * 此方法能将第一个转第二个无论是否DTO
     * @param po 赋值的对象
     * @param dto 被赋值的对象
     * @return
     * @throws Exception
     */
    public static Object poToDto(Object po, Object dto) throws Exception {
        Class poClass = po.getClass();
        Class dtoClass = dto.getClass();
        // 取得po对象的所有属性
        Field[] poFields = poClass.getDeclaredFields();
        //取父类的所有属性
        Field[] superPoFields = poClass.getSuperclass().getDeclaredFields();
        //合并数组
        poFields = (Field[]) mergeArray(poFields,superPoFields);

        // 遍历拼接dto的set方法字段表示
        for (Field f : poFields) {
            String fieldName = f.getName();
            //取得当前get，set字符串表达形式
            String dtoSetMethodName = "set" + firstToBig(fieldName);
            String poGetMethodName = "get"+firstToBig(fieldName);

            //System.out.println(fieldName + "=====" + dtoSetMethodName);
            // 取得DTO对象的set方法
            Method dtoSetMethod=null;
            try {
                dtoSetMethod = dtoClass.getMethod(dtoSetMethodName, f.getType());
            }catch (NoSuchMethodException e) {//如果不存在此方法跳过，
                continue;
            }
            //取得Po对象的get方法
            Method poGetMethod = poClass.getMethod(poGetMethodName, null);
            // 将po对象的属性值set到dto对象中去
            dtoSetMethod.invoke(dto, poGetMethod.invoke(po, null));
        }
        return dto;

    }
    /**
     * 首字母大写
     *
     * @param fieldName
     * @return
     */
    public static String firstToBig(String fieldName) {
        if (fieldName != null && fieldName != "") {
            fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        }
        return fieldName;
    }

    /**
     * 合并数组
     * @param a
     * @param b
     * @return
     */
    public static Object[] mergeArray(Object[] a, Object[] b) {
        Object[] c = Arrays.copyOf(a, a.length+b.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }

}
